import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '../views/Layout'
import ArticleList from '../views/Articles'
import Comment from '../views/Comment'
import Fans from '../views/Fans'
import Home from '../views/Home'
import AddArticle from '../views/Articles/AddArticle'
import EditArticle from '../views/Articles/EditArticle'
import NotFound from '../views/NotFound'
import { getUser } from '@/utils/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'layout',
    component: Layout,
    redirect: '/home',
    children: [
      {
        name: 'ArticleList',
        path: '/articleList',
        component: ArticleList
      },
      {
        name: 'AddArticle',
        path: '/addArticle',
        component: AddArticle
      },
      {
        name: 'EditArticle',
        path: '/editArticle',
        component: EditArticle
      },
      {
        name: 'Comment',
        path: '/comment',
        component: Comment
      },
      {
        name: 'Fans',
        path: '/fans',
        component: Fans
      },
      {
        name: 'Home',
        path: '/home',
        component: Home
      },
      {
        name: 'Image',
        path: '/image',
        component: () => import(/* webpackChunkName: "image" */ '../views/Image/index.vue')
      },
      {
        name: 'Setting',
        path: '/settings',
        component: () => import(/* webpackChunkName: "settings" */ '../views/Setting/index.vue')
      }
    ]
  },
  {
    name: 'Login',
    path: '/login',
    component: () => import(/* webpackChunkName: "login" */ '../views/Login/index.vue')
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  // 注意：一定要放到所有路由定义的最后
  {
    path: '*',
    component: NotFound
  }
]
const router = new VueRouter({
  routes
})
// 添加导航守卫  做页面权限控制
// 守卫逻辑:
// 如果去的是主页 需要进行token验证  如果去的是登录页直接放行
router.beforeEach((to, from, next) => {
  // to:目标路由对象
  // from:起点路由对象
  // next:函数 需要执行才能进行正式的路由跳转
  if (to.path === '/home') {
    // 进行权限验证
    // 如果当前有token数据 就放行  如果没有就调回到登录页面
    const userInfo = getUser()
    if (userInfo) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})
export default router
